﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.Framework.UI.Exceptions;
using PSE.Framework.Common.Validation;

namespace PSE.Framework.UI.Base.Model
{
    [Serializable]
    public class ErrorDetail
    {
        public ErrorDetail(int id)
        {
            _id = id;
        }

        public ErrorDetail(int id, string message)
            : this(id)
        {
            _message = message;
        }

        private int _id;
        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _message;
        public string Message
        {
            get { return _message; }
            set { _message = value; }
        }

        public static ErrorDetail[] CreateFromException(Exception ex)
        {
            if (ex == null)
                throw new ArgumentNullException("ex");

            List<ErrorDetail> details = new List<ErrorDetail>();

            BusinessException exceptionBE;
            ValidationException exceptionVE;

            string message = String.Empty;

            // Business Exception
            if (ex is BusinessException)
            {
                exceptionBE = ex as BusinessException;

                details.Add(new ErrorDetail(exceptionBE.GetHashCode(), exceptionBE.Message));
            }
            // Validation Exception
            else if (ex is ValidationException)
            {
                exceptionVE = ex as ValidationException;

                foreach (ValidationError validationError in exceptionVE.ValidationErrors)
                {
                    details.Add(new ErrorDetail(validationError.GetHashCode(), validationError.ErrorMessage));
                }
            }
            else
            {
                throw new ArgumentException("Invalid exception type, only BusinessException and ValidationException are allowed", "ex");
            }

            return details.ToArray();
        }

        public static bool operator ==(ErrorDetail x, ErrorDetail y)
        {
            if (((object)x) != null && ((object)y) != null)
                return x.Id == y.Id;
            else
                return ((object)x) == null && ((object)y) == null;
        }

        public static bool operator !=(ErrorDetail x, ErrorDetail y)
        {
            return !(x == y);
        }

        public override bool Equals(object obj)
        {
            ErrorDetail e = obj as ErrorDetail;
            if (e != null)
                return this == e;
            else
                return false;
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }
}
